require 'digest/md5'
require 'digest/sha1'

class Auth
  
  def initialize(username, password, method)
    @username = username
    @password = password
    @method = method
  end
  
  def add_to(req)
    wsse(req) if method?:wsse
    app(req) if method?:app
  end
  
  def method?(method)
    @method == method
  end
  
  private
  def wsse(req)
    nonce = Array.new(10){ rand(0x1000000) }.pack('I*')
    nonce_b64 = [nonce].pack("m").chomp
    now = Time.now.gmtime.strftime("%FT%TZ")
    digest = [Digest::SHA1.digest(nonce_b64 + now + @password)].pack("m").chomp

    req['Authorization'] = 'WSSE realm="11870.com", profile="UsernameToken"'
    req['X-WSSE'] = %Q<UsernameToken Username="#{@username}", PasswordDigest="#{digest}", Nonce="#{nonce_b64}", Created="#{now}">
  end
  
  def app(req)
    req['appToken'], req['authSign'] = @username, Digest::MD5.hexdigest( "#{@username}#{@password}" )
  end
  
end



